package com.lagou.rpc.consumer.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;

/**
 * 客户端处理类
 *
 */
@Component
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    ChannelHandlerContext context;

    //发送的消息
    String requestMsg;

    //服务端的消息
    String responseMsg;




    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("收到连接");
        context = ctx;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        responseMsg=msg;
        System.out.println("读取数据");
        //唤醒等待的线程
        notify();
        System.out.println("通知收到");
    }

    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(requestMsg);
        System.out.println("客户端发送消息"+requestMsg);
        //线程等待
        wait();
        return responseMsg;
    }

    public String getRequestMsg() {
        return requestMsg;
    }

    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }
}
